import {
  debounce,
} from 'lodash'
import iView from 'view-design'
import {
  getToken,
} from '@/store'

import api, {
  requestFormDataInterceptor,
  requestFormDataTransform,
  responseTransform,
} from '@/api'

const showError = debounce(message => {
  iView.Message.error({
    content: message,
    duration: 4,
    closable: true,
  })
}, 100)

// api.setBaseURL('branch')

api.setDefaultOptions({
  useFormData: true, // 转换表单数据
})

api.on('request:transform', requestFormDataTransform)
api.on('request:success', requestFormDataInterceptor)
api.on('request:success', config => {
  const token = getToken()
  config.headers['x-auth-token'] = token
  config.params = config.params || {}
  config.params.token = token
  return config
})
api.on('response:transform', responseTransform)
api.on('response:error', (error) => {
  console.log(error)

  if (error.code === 302) {
    return showError('用户没有登录或者超时，请重新登录！')
  }

  showError(error.message)
})
